#include "stopwatch.h"

StopWatch::StopWatch()
{
    totalTicks = 0;
    tick0 = -1;
    running = false;
}

bool StopWatch::start()
{
    if( running )
        return false;
    tick0 = mta_get_clock(0);
    running = true;
    return true;
}

bool StopWatch::stop()
{
    if( !running )
        return false;
    totalTicks += mta_get_clock(0) - tick0;
    running = false;
    return true;
}

void StopWatch::toggle()
{
    int ticks = mta_get_clock(0);
    if( running )
        totalTicks += ticks - tick0;
    else
        tick0 = ticks;
    running = !running;
}

void StopWatch::clear()
{
    tick0 = -1;
    running = false;
    totalTicks = 0;
}

double StopWatch::elapsed()
{
    int ticks = totalTicks;
    if( running )
    {
        ticks += mta_get_clock(0) - tick0;
    }
    return (double)ticks / mta_clock_freq();
}